var common = require('../../../util/common');

module.exports = function(app) {
    return new Handler(app);
};

var Handler = function(app) {
    this.app = app;
    this.statusService = this.app.get('statusService');
};


/**
 * Notify 全局广播
 */
Handler.prototype.global_broadcast = function(msg, session, next) {
    var globalChannelService = this.app.get('globalChannelService');
    var cachedb = this.app.get('cachedb');
    cachedb.asyncGet(session.uid, function (err, data) {
        if (err) throw new Error('asyncGet redis failed!');
        var player = JSON.parse(data);
        globalChannelService.pushMessage('account', 'onChat', {type: 1, msg: player.name + ': ' + msg.msg}, "global_users", null, function(err) {
            if (err) throw new Error('globalChannelService pushMessage failed!');
        });
    });
    common.invokeCallback(next, null);
};

/**
 * 私聊
 */
Handler.prototype.private_chat = function(msg, session, next) {
    if (session.uid === msg.uid) {
        next(null, {
            code: 500,
            msg: '不能给自己发消息'
        });
        return;
    }
    var statusService = this.statusService;
    var cachedb = this.app.get('cachedb');
    statusService.getSidsByUid(msg.uid, function(err, list) {
        if (err) throw new Error('pomelo status plugin called getSidsByUid failed!');
        // duplicate log in
        if (list.length === 0) {
            next(null, {
                code: 200,
                msg: '玩家不在线'
            });
            return;
        } else {
            cachedb.asyncGet(session.uid, function (err, data) {
                if (err) throw new Error('asyncGet redis failed!');
                var player = JSON.parse(data);
                statusService.pushByUids([msg.uid], 'onChat', {type: 3, msg: player.name + ': ' + msg.msg}, function(err) {
                    if (err) throw new Error('statusService pushByUids failed!');
                });
                next(null, {
                    code: 200,
                    msg: '私聊发送成功'
                });
            });
        }
    });
};

// 场景聊天
Handler.prototype.scene_chat = function(msg, session, next) {
    // 场景聊天
    this.app.rpc.scene.remoteHandler.chat(session.get('scene'), msg, session.uid, null);
    common.invokeCallback(next, null);
};
